package com.threefivework.mymall.util;

import com.google.common.collect.Lists;
import com.threefivework.mymall.annotation.Required;
import com.threefivework.mymall.model.domain.TradeDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ForkJoinPool;

/**
 * descripiton: 校验工具
 *
 * @author: kinson(2219945910@qq.com)
 * @date: 2018/6/26
 * @time: 0:43
 * @modifier:
 * @since:
 */
public class CheckUtil {

    private static final Logger logger = LoggerFactory.getLogger(CheckUtil.class);

    private static final ForkJoinPool FORK_JOIN_POOL = new ForkJoinPool(2);

    public static void checkIsRequired(Object bean) throws Exception {
        List<String> requiredFields = Lists.newArrayList();
        List<Field> fields = new ArrayList(Arrays.asList(bean.getClass().getDeclaredFields()));
        fields.addAll(Arrays.asList(bean.getClass().getSuperclass().getDeclaredFields()));
        Iterator var3 = fields.iterator();

        while (var3.hasNext()) {
            Field field = (Field) var3.next();

            try {
                boolean isAccessible = field.isAccessible();
                field.setAccessible(true);
                if (field.isAnnotationPresent(Required.class) && (field.get(bean) == null
                        || field.get(bean) instanceof String && StringUtils.isBlank(field.get(bean).toString()))) {
                    requiredFields.add(field.getName());
                }

                field.setAccessible(isAccessible);
            } catch (IllegalArgumentException | IllegalAccessException | SecurityException var6) {
                var6.printStackTrace();
            }
        }

        if (!requiredFields.isEmpty()) {
            String msg = "必填字段 " + requiredFields + " 必须提供值";
            logger.debug(msg);
            throw new Exception(msg);
        }
    }

    public static void main(String[] args) throws Exception {
        TradeDTO tradeDTO = new TradeDTO();
        tradeDTO.setName("test");
        CheckUtil.checkIsRequired(tradeDTO);
    }
}
